package com.zz.tijian.handle.redis;

import com.zz.tijian.expections.CommonException;
import com.zz.tijian.handle.aliMessage.CodeGenerationUtil;
import com.zz.tijian.handle.aliMessage.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.ExecutionException;

@Component
@Slf4j
public class CodeUtil {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private MessageUtil messageUtil;

    public static int TIMEOUT_MINUTE = 5; // 验证码有效时间,单位分钟
    public static int MAX_REQUESTS = 60; // 时间窗口内允许的最大请求数
    public static int TIME_WINDOW = 60; // 时间窗口大小，单位秒

    public boolean limit(String phone) {
        String requestKey = "RequestLimit" + phone + ":timestamps";

        try (Jedis jedis = jedisPool.getResource()) {
            long now = System.currentTimeMillis();
            long startWindow = now - TIME_WINDOW * 1000;

            // 移除时间窗口外的时间戳
            jedis.zremrangeByScore(requestKey, 0, startWindow);
            // 获取当前时间窗口内的请求数量
            long requestCount = jedis.zcard(requestKey);

            if (requestCount >= MAX_REQUESTS) {
                log.info("请求过于频繁，限流中...");
                return false;
            }
            // 记录当前请求的时间戳
            jedis.zadd(requestKey, now, String.valueOf(now));
            return true;
        }
    }
    // 获取验证码
    public boolean getRedisCode(String phone) throws ExecutionException, InterruptedException {
        // 拼接key
        String codeKey = "VerifyCode" + phone + ":code";
        try (Jedis jedis = jedisPool.getResource()) {
            if (jedis.exists(codeKey)) {
                return false;
            }
            // 发送验证码到redis里面
            String vcode = CodeGenerationUtil.generateCode();
            log.info("验证码：{}", vcode);
            jedis.setex(codeKey, TIMEOUT_MINUTE * 60, vcode); // 过期时间
            messageUtil.sendMessage(vcode, phone);
            return true;
        }
    }

    // 验证码校验
    public boolean verifyCode(String phone, String code) {
        String codeKey = "VerifyCode" + phone + ":code";

        try (Jedis jedis = jedisPool.getResource()) {
            String redisCode = jedis.get(codeKey);
            return redisCode != null && redisCode.equals(code);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常，可以根据需要进行日志记录或者其他处理
            return false;
        }
    }
}
